<template>
  <div class="page">
      <!-- 修改头像 -->
      <div v-if="action === 'changeAvatar'" class="box">
        <h2>修改头像</h2>
        <form @submit.prevent="changeAvatar">
          <img :src="previewUrl || user.avatar || defaultAvatar" alt="头像" class="large-avatar" />
          <div class="input-upload">
            <label class="upload-label">
              <input type="file" @change="handleFileChange" accept="image/jpeg, image/png" class="file-input"/>
              选择头像
            </label>
          </div>
          <small>仅支持格式为 JPG 和 PNG 的图片，大小不超过2MB</small>
          <div class="buttons">
            <button class="return-btn" @click="goToHomePage">返回</button>
            <button type="submit" class="edit-btn">修改</button>
          </div>
        </form>
      </div>
      <!-- 修改昵称 -->
      <div v-if="action === 'changeUsername'" class="box">
        <h2>修改昵称</h2>
        <form @submit.prevent="changeUsername">
          <div class="input-group">
            <input type="text" id="username" v-model="user.username" placeholder="昵称必须为1~10个字符" />
          </div>
          <div class="buttons">
            <button class="return-btn" @click="goToHomePage">返回</button>
            <button type="submit" class="edit-btn">修改</button>
          </div>
        </form>
      </div>
      <!-- 修改密码 -->
      <div v-if="action === 'changePassword'" class="box">
        <h2>修改密码</h2>
        <form @submit.prevent="changePassword">
          <div class="input-group">
            <label for="oldPassword">原密码</label>
            <input type="password" id="oldPassword" v-model="pwdData.oldPassword" placeholder="请输入原密码" />
          </div>
          <div class="input-group">
            <label for="newPassword">新密码</label>
            <input type="password" id="newPassword" v-model="pwdData.newPassword" placeholder="新密码必须包含数字和字母，且长度至少8位" />
          </div>
          <div class="input-group">
            <label for="confirmPassword">确认密码</label>
            <input type="password" id="confirmPassword" v-model="pwdData.confirmPassword" placeholder="请确认密码" />
          </div>
          <div class="buttons">
            <button class="return-btn" @click="goToHomePage">返回</button>
            <button type="submit" class="edit-btn">修改</button>
          </div>
        </form>
      </div>
      <!-- 展示个人资料 -->
      <div v-if="action === 'default'" class="box">
        <h2>个人资料</h2>
        <div class="user-info">
          <p><strong>用户名：</strong> {{ user.username }}</p>
          <p><strong>电子邮件：</strong> {{ user.email }}</p>
        </div>
        <div class="buttons">
          <button class="return-btn" @click="goToHomePage">返回</button>
          <button class="edit-btn" @click="editProfile">修改</button>
        </div>
      </div>
  </div>
</template>

<script>
import defaultAvatar from "@/assets/default-avatar.png";
import {userChangeNameService, userModifyPasswordService,userUploadAvatarService} from "@/api/user";
import request from "@/utils/request";

export default {
  data() {
    return {
      user: {
        email: '',
        username: '',
        avatar: '',
      },
      pwdData:{
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      defaultAvatar: defaultAvatar, //默认头像
      action: this.$route.query.action || 'default',
      selectedFile: null,       // 用于存储选择的文件
      previewUrl: null          // 用于预览的临时 URL
    };
  },
  methods:{
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file; // 保存选择的文件
        this.previewUrl = URL.createObjectURL(file); // 创建预览 URL
      }
    },

    async changeAvatar() {
      if (!this.selectedFile) {
        alert("请先选择并上传头像");
        return;
      }
      const formData = new FormData();
      formData.append("file", this.selectedFile);

      // 打印 FormData 内容，确认文件已添加
      for (let pair of formData.entries()) {
        console.log(pair[0]+ ', ' + pair[1]);
      }
      try {
        let result = await userUploadAvatarService(formData);
        if (result.code === "0") {
          this.user.avatar = result.data; // 更新头像 URL
          // try {
          //   // 使用 request 工具类请求头像Blob数据
          //   const response = await request.get(result.data.avatar, {
          //     responseType: "blob"
          //   });
          //   // 将 Blob 数据转换为 URL
          //   this.user.avatar = URL.createObjectURL(response);
            //更新localStorage
          const Info = JSON.parse(localStorage.getItem('userInfo'));
          Info.avatar = this.user.avatar; // 更新头像
          localStorage.setItem('userInfo', JSON.stringify(Info)); // 保存更新后的 userInfo
          alert("头像更新成功！");
          // } catch (error) {
          //   console.error("Failed to load avatar image:", error);
          //   alert("头像更新失败，请重试！");
          // }
          this.previewUrl = null; // 清除预览 URL
          this.$router.push('/');
        } else {
          alert(result.message ? result.message : "头像更新失败");
        }
      } catch (error) {
        alert("上传失败：" + error.message);
      }
    },
    async changeUsername() {
      if (this.user.username) {
        let result = await userChangeNameService(this.user.username);
        if (result.code === "0") {
          alert('修改成功！');
          localStorage.setItem('token', result.data);
          this.$router.push('/');
        }
        else{
          alert(result.message ? result.message : '修改失败！');
        }
      }
      else {
        alert('请填写表单');
      }
    },
    async changePassword() {
      if (this.pwdData.newPassword !== this.pwdData.confirmPassword) {
        alert('两次输入的密码不一致');
        return;
      }
      if (this.pwdData.oldPassword && this.pwdData.newPassword) {
        let result = await userModifyPasswordService(this.pwdData);
        if (result.code === "0") {
          alert('修改成功！请重新登录。');
          localStorage.clear();
          this.$router.push('/');
        } else {
          alert(result.message ? result.message : '修改失败！请重新填写。');
        }
      }else {
        alert('请完整填写表单');
      }
    },
    goToHomePage() {
      this.$router.push('/');
    }
  },

};
</script>

<style scoped>
.page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #111;
  color: #fff;
}

.box {
  width: 400px;
  padding: 20px;
  background-color: #222;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #ffcd00;
}

.input-upload {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.upload-label {
  display: inline-block;
  padding: 8px 16px;
  color: #000;
  background-color: #ffcd00;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: background-color 0.3s;
}

.upload-label:hover {
  background-color: #ffcd00;
}

small {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  display: inline-block;
}

.file-input {
  display: none;
}

.input-group {
  margin-bottom: 20px;
  text-align: left;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
}

.input-group input {
  width: 90%;
  padding: 10px;
  border: 1px solid #333;
  border-radius: 5px;
  background-color: #333;
  color: #fff;
  font-size: 16px;
}

.input-group input::placeholder {
  color: #aaa;
}

.large-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.user-info p {
  margin: 10px 0;
}

.buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.edit-btn, .return-btn {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #ffcd00;
  border: none;
  border-radius: 5px;
  color: #000;
  cursor: pointer;
  width: 45%;
}

.edit-btn:hover, .return-btn:hover {
  background-color: #e5b800;
}
</style>